import React, { useState, useRef, useEffect } from 'react';
import { CheckOutlined, ArrowRightOutlined } from '@ant-design/icons';

interface SliderCaptchaProps {
  onSuccess: () => void;
  onReset?: () => void;
  width?: number;
  height?: number;
  text?: string;
  successText?: string;
}

const SliderCaptcha: React.FC<SliderCaptchaProps> = ({
  onSuccess,
  onReset,
  width,
  height = 40,
  text = '请拖动滑块完成验证',
  successText = '验证成功'
}) => {
  const [isDragging, setIsDragging] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  const [sliderLeft, setSliderLeft] = useState(0);
  const [startX, setStartX] = useState(0);
  const sliderRef = useRef<HTMLDivElement>(null);
  const trackRef = useRef<HTMLDivElement>(null);

  const [containerWidth, setContainerWidth] = useState(width || 300);
  const sliderWidth = 40;
  const maxLeft = containerWidth - sliderWidth;

  useEffect(() => {
    if (!width && trackRef.current) {
      const updateWidth = () => {
        const rect = trackRef.current?.getBoundingClientRect();
        if (rect) {
          setContainerWidth(rect.width);
        }
      };
      updateWidth();
      window.addEventListener('resize', updateWidth);
      return () => window.removeEventListener('resize', updateWidth);
    } else if (width) {
      setContainerWidth(width);
    }
  }, [width]);

  const handleMouseDown = (e: React.MouseEvent) => {
    if (isSuccess) return;
    setIsDragging(true);
    setStartX(e.clientX - sliderLeft);
  };

  const handleTouchStart = (e: React.TouchEvent) => {
    if (isSuccess) return;
    setIsDragging(true);
    setStartX(e.touches[0].clientX - sliderLeft);
  };

  const handleMouseMove = (e: MouseEvent) => {
    if (!isDragging || isSuccess) return;
    
    const newLeft = Math.max(0, Math.min(maxLeft, e.clientX - startX));
    setSliderLeft(newLeft);

    // 检查是否滑动到最右边
    if (newLeft >= maxLeft - 5) {
      setIsSuccess(true);
      setIsDragging(false);
      setSliderLeft(maxLeft);
      onSuccess();
    }
  };

  const handleTouchMove = (e: TouchEvent) => {
    if (!isDragging || isSuccess) return;
    
    const newLeft = Math.max(0, Math.min(maxLeft, e.touches[0].clientX - startX));
    setSliderLeft(newLeft);

    // 检查是否滑动到最右边
    if (newLeft >= maxLeft - 5) {
      setIsSuccess(true);
      setIsDragging(false);
      setSliderLeft(maxLeft);
      onSuccess();
    }
  };

  const handleMouseUp = () => {
    if (!isDragging || isSuccess) return;
    
    setIsDragging(false);
    // 如果没有滑动到最右边，重置位置
    if (sliderLeft < maxLeft - 5) {
      setSliderLeft(0);
    }
  };

  const handleTouchEnd = () => {
    if (!isDragging || isSuccess) return;
    
    setIsDragging(false);
    // 如果没有滑动到最右边，重置位置
    if (sliderLeft < maxLeft - 5) {
      setSliderLeft(0);
    }
  };

  const reset = () => {
    setIsSuccess(false);
    setSliderLeft(0);
    setIsDragging(false);
    onReset?.();
  };

  useEffect(() => {
    if (isDragging) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
      document.addEventListener('touchmove', handleTouchMove);
      document.addEventListener('touchend', handleTouchEnd);
    }

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
      document.removeEventListener('touchmove', handleTouchMove);
      document.removeEventListener('touchend', handleTouchEnd);
    };
  }, [isDragging, startX, sliderLeft, maxLeft]);

  return (
    <div className="slider-captcha-container">
      <div 
        ref={trackRef}
        className={`relative border-2 rounded-lg overflow-hidden select-none transition-all duration-300 ${
          isSuccess 
            ? 'border-green-400 bg-green-50' 
            : isDragging 
            ? 'border-blue-400 bg-blue-50' 
            : 'border-gray-300 bg-gray-100'
        }`}
        style={{ width: width || '100%', height }}
      >
        {/* 背景文字 */}
        <div className="absolute inset-0 flex items-center justify-center text-sm text-gray-500 font-medium pointer-events-none">
          {isSuccess ? successText : text}
        </div>

        {/* 进度条 */}
        <div 
          className={`absolute left-0 top-0 h-full transition-all duration-300 ${
            isSuccess ? 'bg-green-200' : 'bg-blue-200'
          }`}
          style={{ width: sliderLeft + sliderWidth }}
        />

        {/* 滑块 */}
        <div
          ref={sliderRef}
          className={`absolute top-0 flex items-center justify-center cursor-pointer transition-all duration-300 ${
            isSuccess 
              ? 'bg-green-500 text-white' 
              : isDragging 
              ? 'bg-blue-500 text-white shadow-lg' 
              : 'bg-white text-gray-600 shadow-md hover:shadow-lg'
          }`}
          style={{
            left: sliderLeft,
            width: sliderWidth,
            height: height - 4,
            top: 2,
            borderRadius: '6px'
          }}
          onMouseDown={handleMouseDown}
          onTouchStart={handleTouchStart}
        >
          {isSuccess ? (
            <CheckOutlined className="text-lg" />
          ) : (
            <ArrowRightOutlined className="text-lg" />
          )}
        </div>
      </div>

      {/* 重置按钮 */}
      {isSuccess && (
        <button
          onClick={reset}
          className="mt-2 text-xs text-gray-500 hover:text-gray-700 underline"
        >
          重新验证
        </button>
      )}
    </div>
  );
};

export default SliderCaptcha;